<template>
  <div id="app">
    <!-- 头部 -->
    <header class="header">
      <div>
        <nav class="nav">
          <ul>
            <li><a class="logo">家庭 KTV</a></li>
            <li><a @click="onMV" :class="{ 'active': listType == 'MV' }">MV</a></li>
            <li><a @click="load" :class="{ 'active': !listType }">榜单</a></li>
            <li><a @click="listType = 'SingerList'" :class="{ 'active': listType == 'SingerList' }">歌手</a></li>
            <li><a href="#">分类</a></li>
            <!-- <li><a href="#">本地</a></li> -->
          </ul>
        </nav>
      </div>
      <div class="search-box">
        <input type="text" placeholder="搜索歌曲或歌手">
        <button>搜索</button>
        <button @click="showPlayInfo">已点歌曲</button>
      </div>
    </header>
    <!-- 歌词显示区域 -->
    <KrcParser v-if="currentSong && currentKrcContent" :krcContent="currentKrcContent"
      :currentTime="audioData.currentTime" @changeImageUrl="onChangeImageUrl" :id="currentSong?.mvId" />
    <!-- MV播放模块 -->
    <Img v-if="listType == 'MV'" :imageUrl="imageUrl" :id="currentSong?.mvId" class="MV" />
    <!-- 音频播放器，初始隐藏 -->
    <audio ref="audioPlayer" @timeupdate="updateProgress" @loadeddata="onLoadSong" @loadstart="onLoadStart" controls
      style="display: none;"></audio>
    <!-- 已点歌曲 -->
    <Popup v-model="isPopupVisible" :songs="nextSongList" :width="500" />
    <main class="main" v-if="listType != 'MV'">
      <template v-if="listType">
        <SingerList v-if="listType == 'SingerList'" @singer="onSinger" />
      </template>
      <HotSongList v-else :songs="songs" :isLoading="isLoading" :errorMessage="errorMessage" @addToNext="addToNext" />
    </main>
    <!-- 底部模块 -->
    <footer class="footer" :style="{ position: listType == 'MV' ? 'absolute' : 'static' }">
      <div>
        <button @click="toggleOriginalSound">原唱</button>
        <!-- <button @click="rewind">快退</button> -->
        <button @click="togglePlayPause">
          {{ isPlaying ? '暂停' : '播放' }}
        </button>
        <button @click="fastForward">快进</button>
        <button @click="playNext">下一首</button>
        <button @click="replay">重唱</button>
      </div>
      <div>
        <div v-if="currentSong">
          <div class="current-song">
            <button>当前播放: {{ currentSong.title }} - {{ currentSong.artist }}</button>
          </div>
          <!-- 添加加载提示 -->
          <div v-if="!audioData.duration" class="loading-info">加载中...</div>
          <div class="time-info" v-if="audioData.duration">
            {{ formatTime(audioData.currentTime) }} / {{ formatTime(audioData.duration) }}
          </div>
        </div>
        <div v-else class="current-song">
          <button>当前播放: 无 - 请先添加歌曲！</button>
        </div>
      </div>
    </footer>
    <!-- 播放器模块 -->
    <!-- <template v-if="listType != 'MV'">
      <div class="player-module" v-if="currentSong">
        <div class="current-song">
          <div class="info">当前播放: {{ currentSong.title }} - {{ currentSong.artist }}</div>
        </div>
        <input type="range" min="0" :max="audioData.duration || 0" v-model="audioData.currentTime"
          @input="audioData.currentTime = $event.target.value" class="progress-bar" />
        <div v-if="!audioData.duration" class="loading-info">加载中...</div>
        <div class="time-info" v-if="audioData.duration">
          {{ formatTime(audioData.currentTime) }} / {{ formatTime(audioData.duration) }}
        </div>
      </div>
      <div class="player-module" v-else>
        <div class="current-song">
          当前播放: 无 - 请先添加歌曲！
        </div>
      </div>
    </template> -->
    <!-- 弹出框 -->
    <Popup v-model="isPopupShow" :message="popupMessage" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import HotSongList from './HotSongList.vue';
import Popup from './components/Popup.vue';
import SingerList from './SingerList.vue';
import KrcParser from './KrcParser.vue';
import MV from './MV.vue';
import Img from './Img.vue';

const ww = computed(() => window.innerWidth);

// 定义响应式数据
const songs = ref([]);
const audioPlayer = ref(null);
const audioData = ref({});
// 加载状态
const isLoading = ref(true);
// 错误信息
const errorMessage = ref('');
// 待播放歌曲列表
const nextSongList = ref([]);
// 当前播放的歌曲
const currentSong = ref(null);
// 当前歌曲的 KRC 歌词内容
const currentKrcContent = ref('');
// 当前歌曲索引
const songIndex = ref(-1);
// 播放状态
const isPlaying = ref(false);
// 假设原唱和伴唱 URL 规则，这里简单用 _original 后缀表示原唱
const hasOriginalSound = ref(false);
// 弹出框显示状态
const isPopupVisible = ref(false);
// 弹出框消息内容
const popupMessage = ref('');
// 弹出框消息
const isPopupShow = ref(false);
// 中间列表类型
const listType = ref('');

const imageUrl = ref(undefined);

const onChangeImageUrl = (url) => {
  if (url && imageUrl.value !== url)
    setTimeout(() => { // 延迟确保过渡效果能看到
      imageUrl.value = undefined; // 隐藏图片，触发淡出效果，然后重新显示以触发淡入效果
      setTimeout(() => { // 再次延迟确保过渡效果完成
        imageUrl.value = url; // 重新显示图片，触发淡入效果
      }, 500); // 延迟时间应与CSS中的transition时间一致或更长
    }, 0);
}

const alert = msg => {
  popupMessage.value = msg;
  isPopupShow.value = true;
}

const isNotPlaySong = () => {
  if (!currentSong.value) {
    alert('请先添加歌曲！')
    return true;
  }
  return false;
}

// 选择歌手
const onSinger = async (name) => {
  await load();
  songs.value = songs.value.filter(o => o.artist === name);
}

// 定义添加歌曲到下一首播放的函数
const addToNext = (song) => {
  nextSongList.value.push(song);
  if (!currentSong.value) {
    playNext();
  }
};

// 定义播放歌曲的函数
const playSong = async (song) => {
  currentSong.value = song;
  try {
    songIndex.value = songs.value.findIndex((s) => s.id === song.id);
    audioPlayer.value.src = song.url;
    audioPlayer.value.play();
    isPlaying.value = true;
    if (song.krc) {
      // 加载歌词
      const krcResponse = await axios.get(song.krc);
      currentKrcContent.value = krcResponse.data;
    } else {
      currentKrcContent.value = '';
    }
    // 预加载四张图片
    const img = new Image();
    img.src = '/song/' + song.mvId + '/1.png';
    img.src = '/song/' + song.mvId + '/2.png';
    img.src = '/song/' + song.mvId + '/3.png';
    img.src = '/song/' + song.mvId + '/4.png';
  } catch (error) {
    console.error('获取歌词失败:', error);
  }
  // 检查是否有原唱版本
  // hasOriginalSound.value = song.url.includes('_accompaniment');
};

// 监听音频播放结束事件，播放下一首歌曲
const handleEnded = () => {
  if (nextSongList.value.length > 0) {
    const next = nextSongList.value.shift();
    playSong(next);
    return;
  }
  currentSong.value = null;
};

// 快退
const rewind = () => {
  if (isNotPlaySong()) return;
  audioPlayer.value.currentTime -= 10;
};

// 切换播放和暂停状态
const togglePlayPause = () => {
  if (isNotPlaySong()) return;
  if (isPlaying.value) {
    audioPlayer.value.pause();
    if (mvRef.value) mvRef.value.pause();
  } else {
    audioPlayer.value.play();
    if (mvRef.value) mvRef.value.play();
  }
  isPlaying.value = !isPlaying.value;
};

// 快进
const fastForward = () => {
  if (isNotPlaySong()) return;
  audioPlayer.value.currentTime += 10;
};

// 播放下一首
const playNext = () => {
  if (nextSongList.value.length > 0) {
    const next = nextSongList.value.shift();
    playSong(next);
    return;
  } else {
    alert('没有下一首歌曲了，请先添加')
  }
};

// 重唱
const replay = () => {
  if (isNotPlaySong()) return;
  audioPlayer.value.currentTime = 0;
  audioPlayer.value.play();
  isPlaying.value = true;
};

// 显示播放信息的函数
const showPlayInfo = () => {
  if (nextSongList.value.length === 0) {
    alert('没有下一首歌曲了，请先添加');
    return;
  }
  isPopupVisible.value = true;
};
const mvRef = ref(null);
// 监听播放器帧率
const updateProgress = () => {
  audioData.value.currentTime = audioPlayer.value.currentTime;
  audioData.value.duration = audioPlayer.value.duration;
  if (mvRef.value && listType.value === 'MV') {
    mvRef.value.syncTime(audioData.value.currentTime);
  }
};

const onMV = () => {
  if (isNotPlaySong()) return;
  listType.value = 'MV';
  if (mvRef.value) {
    mvRef.value.play();
  }
}

// 监听播放器加载
const onLoadSong = o => {
  console.log('音频加载完成', o);
}
const onLoadStart = o => {
  console.log('音频开始加载', o);
}

// 格式化时间
const formatTime = (time) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

const load = async () => {
  try {
    isLoading.value = true;
    const response = await axios.get('/song/song.json');
    songs.value = response.data;
  } catch (error) {
    errorMessage.value = '获取歌曲数据失败，请稍后重试。';
    console.error('获取歌曲数据失败:', error);
  } finally {
    // 无论成功还是失败，都将加载状态设置为 false
    isLoading.value = false;
    listType.value = '';
  }
}

// 在组件挂载时获取歌曲数据
onMounted(() => {
  load();
  // 绑定音频播放结束事件
  audioPlayer.value.addEventListener('ended', handleEnded);
});
</script>

<style scoped>
/* 全局样式 */
#app {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: url('@/assets/img/icon_main_bg.webp') no-repeat center center fixed;
  background-size: cover;
  margin: 0;
  padding: 0;
}

/* 头部导航栏样式 */
.header {
  color: white;
  display: grid;
  justify-items: start;
  grid-template-columns: var(--td-columns);
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-weight: bold;
  margin-right: 1rem;
}

.nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
}

.nav li {
  margin-right: 1.5rem;
}

.nav a {
  color: white;
  text-decoration: none;
  transition: color 0.3s ease;
}

.nav a:hover {
  color: #3498db;
}

.nav a.active {
  color: #3498db;
  font-weight: bold;
}

.search-box {
  display: flex;
  align-items: center;
}

.search-box input {
  padding: 0.5rem;
  border: none;
  border-radius: 4px 0 0 4px;
}

/* 音频播放器样式 */
.audio-player {
  display: block;
  margin: 2rem auto;
  width: 100%;
  max-width: 600px;
}

.footer button {
  opacity: 0.3;
}

.footer button:hover {
  opacity: 0.8;
  background-color: #2980b9;
}

/* 播放器模块样式 */
.player-module {
  border-radius: 8px;
  text-align: center;
}

.current-song {
  display: flex;
  margin-left: 1rem;
  /* 使用 flexbox 布局 */
  justify-content: center;
  /* 水平居中 */
  align-items: center;

  button {
    background-color: transparent;
  }

  button:hover {
    background-color: transparent;
  }
}

.progress-bar {
  width: 60%;
}

.time-info {
  font-size: 0.9rem;
  color: #777;
}

/* 加载提示样式 */
.loading-info {
  color: #777;
  font-size: 0.9rem;
  margin-bottom: 5px;
}
</style>